<template>
    <div class="p-15 p-t-0">
        <div class="table-padding orderDialog">
            <el-form :model="modelForm" ref="modelForm" >
                <el-row>
                    <el-col :span="7">
                        <el-form-item  prop="supplier" :rules="[]" >
                            <div class="el-input el-input-group el-input-group--prepend">
                                <div class="el-input-group__prepend">供应商</div>
                                <el-select v-model="modelForm.supplier" filterable placeholder="请选择供应商" style="width: 100%">
                                    <el-option
                                            v-for="item in suppliers"
                                            :key="item.id"
                                            :label="item.name"
                                            :disabled="item.state!='NORMAL'"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7" :offset="1">
                        <el-form-item prop="createAt" :rules="[]">
                            <div class="el-input el-input-group el-input-group--prepend">
                                <div class="el-input-group__prepend">订单日期</div>
                                <el-date-picker
                                    v-model="modelForm.createAt"
                                    align="right"
                                    type="date"
                                    style="width: 100%"
                                    placeholder="选择日期"
                                    :picker-options="pickerOptions0">
                                </el-date-picker>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="1">
                        <el-form-item prop="warehouse" :rules="[]">
                            <div class="el-input el-input-group el-input-group--prepend">
                                <div class="el-input-group__prepend">仓库</div>
                                <el-select v-model="modelForm.warehouse"  placeholder="请选择" style="width: 100%">
                                    <el-option
                                            v-for="item in warehouses"
                                            :key="item.id"
                                            :label="item.name"
                                            :disabled="item.state!='NORMAL'"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item  prop="address" :rules="[]">
                    <el-input type="text" v-model="modelForm.address"  auto-complete="off" placeholder="请输入收货地址">
                        <template slot="prepend">
                            <el-button>收货地址</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item  prop="remark" :rules="[]">
                    <el-input type="text" v-model="modelForm.remark"  auto-complete="off" placeholder="请输入备注信息">
                        <template slot="prepend">
                            <el-button>备注</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
        </div>
        <div class="orderTable">
            <div class="functionButton text-left m-b-10">
                <el-button type="primary" @click="submitForm('modelForm')"><i class="icon icon-baocun"></i> 保存</el-button>
                <el-button  type="success" @click="resetForm('modelForm')"><i class="icon icon-tijiao"></i> 提交并审核</el-button>
                <el-button type="danger" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    show-summary
                    :summary-method="getSummaries"
                    style="width: 100%">
                <el-table-column
                        type="index"
                        width="50">
                </el-table-column>
                <el-table-column
                        width="80">
                    <template scope="scope">
                        <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addColumn(scope.$index)"></span>
                        <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusColumn(scope.$index)"></span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="code"
                        label="原料编码"
                        width="150">
                    <template scope="scope">
                        <div style="position: relative">
                            <el-select v-model="scope.row.code"  remote @change="codeChange(scope.$index)"   :filterable="true"  placeholder="请输入原料编码" >
                                <el-option v-for="item in material" :disabled="item.state!='NORMAL'" :key="item.label" :label="item.value+' ['+item.purchaseUnit+']'" :value="item.label">
                                </el-option>
                            </el-select>
                            <span class="el-icon-more" @click="handleIconClick(scope.$index)"  style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="原料名称"
                        width="250" >
                </el-table-column>
                <el-table-column
                        prop="goodsSpec"
                        label="规格型号"
                        width="80">
                </el-table-column>
                <el-table-column
                        prop="purchaseSpec"
                        label="采购规格"
                        width="80">
                </el-table-column>
                <el-table-column
                        prop="unitName"
                        label="采购单位"
                        width="80">
                </el-table-column>
                <el-table-column
                        prop="count"
                        label="采购数量"
                        width="100">
                    <template scope="scope">
                        <el-input v-model="scope.row.count"  @blur="priceValidate(scope.row,'count')"  placeholder="0.00"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="price"
                        label="采购单价"
                        width="100">
                    <template scope="scope">
                        <el-input v-model="scope.row.price"  @blur="priceValidate(scope.row,'price')"  placeholder="0.00"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="historyPrice"
                        label="历史采购单价"
                        width="100">
                    <template scope="scope">
                        <span>{{scope.row.historyPrice | money}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="money"
                        label="采购金额"
                        width="100">
                    <template scope="scope">
                        <el-input v-model="scope.row.money"  @blur="priceValidate(scope.row,'money')"  placeholder="0.00"></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="memo"
                        label="备注">
                    <template scope="scope">
                        <el-input v-model="scope.row.memo"   placeholder=""></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog  :fullscreen="isScreen" :visible.sync="dialogTableVisible" v-dialogdrag=" { target:'.el-dialog__header',container:'.el-dialog',border:'.el-dialog__wrapper'}" :close-on-click-modal="false" >
            <div slot="title" class="model-title">
                    选原料
                    <span class="title-left-icon">
                        <i class="icon icon-quanping" @click="isScreen=isScreen?false:true"></i>
                    </span>
            </div>
            <div  style="margin-left: 15px;">
                <br>
                <div class="text-left">
                    <el-input placeholder="请输入名称，编码" style="width: 300px" v-model="inputText" >
                        <el-button slot="append"  @click="inputClick" icon="el-icon-search">搜索</el-button>
                    </el-input>
                </div>
                <el-row style="margin-top: 20px">
                    <el-col :span="5" style="height: 100%">
                        <el-tree
                                :data="modelTreeTable"
                                :props="defaultProps"
                                accordion
                                style="height: 400px;overflow-y: auto;background-color: rgb(238, 241, 246);color: #000000;"
                                node-key="id"
                                :default-expanded-keys="[2]"
                                :expand-on-click-node="true"
                                @node-click="handleNodeClick">
                        </el-tree>
                    </el-col>
                    <el-col :span="18"  style="margin-left: 25px;">
                        <el-table :data="modelDataTable"
                                border
                                style="height:400px;overflow-y: auto;"
                                ref="multipleTable"
                                @cell-click="chnageGoodState"
                                @selection-change="handleSelectionChange">
                            <el-table-column
                                    type="selection"
                                    :selectable='checkboxInit'
                                    width="55">
                            </el-table-column>
                            <el-table-column property="no" label="编码"></el-table-column>
                            <el-table-column property="name" label="名称"></el-table-column>
                            <el-table-column property="goodsSpec" label="规格"></el-table-column>
                            <!--<el-table-column property="unit.id" label="采购单位ID" style="display: none"></el-table-column>-->
                            <el-table-column property="purchaseUnit" label="采购单位"></el-table-column>
                            <el-table-column property="unit" label="库存单位"></el-table-column>
                            <el-table-column property="purchaseSpec" label="采购规格"></el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <br>
                <div class="text-center">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page.sync="currentPage"
                            :page-sizes="pageSizes"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                    </el-pagination>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogTableVisible = false">取 消</el-button>
                        <el-button type="primary" @click="tableClick">确 定</el-button>
                    </span>
        </el-dialog>
    </div>
</template>
<script>
export default{
    data(){
        return{
            modelForm:{},
            suppliers:[],
            warehouses:[],
            pickerOptions0: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                }
            },
            tableData:[{
                id:"",
                code: '',
                name: '',
                goodsSpec: '',
                purchaseSpec: '',
                unitName:'',
                count:'0',
                price:'0.00',
                historyPrice:'',
                money:'0.00',
                memo:'',
            }],
            material:[],
            //模态窗数据
            itemActive:"",
            dialogTableVisible:false,
            inputText:"",
            cateId:"",
            modelTreeTable:[],
            modelDataTable:[],
            selectRow:[],
            pageSizes:window.pageSizes,//所有可选择的条数
            pageSize:window.pageSize,//控制一页显示的条数
            total:10,//总条数
            currentPage:1,
            isScreen:false,
            defaultProps: {
                label: 'name'
            },
        }
    },
    created(){
        window.this=this;
        this.initData();
    },
    methods:{
        initData(){
            this.$axios.get("purchaseOrders/create").then((data)=>{
                if(data.status==200){
                    let json = data.content;
                    //初始化单据到表单
                    this.modelForm = json.purchaseOrder;
                    this.suppliers = json.supplier;
                    this.warehouses = json.warehouse;
                    this.material=json.material;
                    this.modelTreeTable=json.treeData;
                    this.modelForm.createAt=json.date;
                }else{
                    this.$message.error(data.body.message);
                }
            })
        },
        addColumn(index){
            this.tableData.splice(index+1,0,{
                id:'',
                code: '',
                name: '',
                goodsSpec: '',
                purchaseSpec: '',
                unitId:'',
                unitName:'',
                count:'0',
                price:'0.00',
                historyPrice:'',
                money:'0.00',
                memo:'',
            })
        },
        minusColumn(index){
            
            if(this.tableData.length>1){
                this.tableData.splice(index,1);
            }else{
                this.$message.info("最少保留一条");
            }
        },
        codeChange(index){
            for(var i=0;i<this.material.length;i++){
                if(this.material[i].label===this.tableData[index].code){
                    this.tableData[index].code=this.material[i].no;
                    this.tableData[index].name=this.material[i].nameValue;
                    for(var m=0;m<this.tableData.length;m++){
                        if(this.material[i].label==this.tableData[m].id){
                                this.$message.info("本次添加含有重复原料");
                            break;
                        }
                    }
                    this.tableData[index].id=this.material[i].label;
                    this.tableData[index].goodsSpec=this.material[i].goodsSpec;
                    this.tableData[index].unitName=this.material[i].purchaseUnit;
                    this.tableData[index].purchaseSpec=this.material[i].purchaseSpec;
                    this.tableData[index].price=(this.material[i].purchasePrice*1).toFixed(2);
                    this.tableData[index].count=0;
                    this.tableData[index].money=(this.tableData[index].price*this.tableData[index].count).toFixed(2);
                    this.tableData[index].historyPrice=this.material[i].purchaseNewPrice;
                    break;
                }
            }
        },
        priceValidate(item,key){
            var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if(!isNum.test(item[key])){
                item[key]="0.00"
            }else{
                item[key]=item[key]
            }
            switch (key){
                case "count":
                    if(!isNaN(item.count)){
                        item.money= item.price*item.count;
                        item.money=item.money.toFixed(2);
                    }else{
                            item.count=0
                    }
                    break;
                case "price":
                    if(!isNaN(item.price)){
                        item.money= item.price*item.count;
                        item.money=item.money.toFixed(2);
                        item.price=(item.price*1).toFixed(2);
                    }else{
                        item.price='0.00';
                    }
                    break;
                case "money":
                    if(!isNaN(item.money) && item.count>0){
                        item.price= item.money/item.count;
                        item.price=item.price.toFixed(2);
                        item.money=(item.money*1).toFixed(2);
                    }else{
                        item.money='0.00';
                    }
                    break;
            }
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                if(index==7 || index==10){
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                if(index==7){
                                    return prev + curr;
                                }else{
                                    return ((prev*1 + curr*1)*1).toFixed(2);
                                }
                            } else {
                                if(index==7){
                                    return prev;
                                }else{
                                    return (prev*1).toFixed(2);
                                }
                                
                            }
                        }, 0);
                    } else {
                        sums[index] = '数据异常';
                    }
                }
            });

            return sums;
        },
        submitForm(formName) {
            this.modelForm.type=1;
            this.validateData(formName);
        },
        resetForm(formName) {
            this.modelForm.type=2;
            this.validateData(formName);
        },
        validateData(fromName){
            if (this.modelForm.warehouse == null) {
                this.$message.error("请选择仓库！");
                return;
            }
            if (this.modelForm.supplier == null) {
                this.$message.error("请选择供应商！");
                return;
            }

            for (var i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].id == "") {
                    if (this.tableData.length == 1) {
                        this.$message.error("请添加单据明细！");
                        return;
                    }
                    this.tableData.splice(i, 1);
                    i--;
                }
                if(this.modelForm.type){
                    if (this.tableData[i].count <= 0) {
                        this.$message.error("数量不能小于1！请检查第"+(i+1)+"行数据");
                        return;
                    }
                }
            }
            if (this.tableData == null || this.tableData.length == 0) {
                this.$message.error("请添加单据明细！");
                return;
            }
            if(this.$route.query.type=="4") {//5 说明是查看
                this.modelForm.id="";
            }
            this.$refs[fromName].validate((valid)=> {
                if (valid) {
                    var data = {};
                    data.modelForm = this.modelForm;
                    data.items = this.tableData;
                    this.$axios.post("purchaseOrders/create",data,"json").then(data=> {
                        if (data.status == 200) {
                            this.$message({
                                message: data.message,
                                type: 'success'
                            });
                            this.$emit('addSuccess');
                            this.goBack();
                        } else {
                            this.$message.error(data.message);
                        }
                    })
                } else {
                    this.$message.error("请检查输入项");
                    return false;
                }
            });
        },
        //以下全是选择菜品所用的方法
        handleIconClick(index){
            this.dialogTableVisible = true;
            this.itemActive = index;
            this.selectGood();
        },
        handleNodeClick(data) {
            this.inputText="";
            this.cateId=data.id;
            this.selectGood();
        },
        selectGood(){           
            this.$axios.get("purchaseOrders/getMaterials?page.pn="+this.currentPage+"&page.size="+this.pageSize+"&search.category.id_eq="+this.cateId+"&search.code_eq="+this.inputText).then(data=>{
                if(data.status==200){
                    var dataValue=data.content;
                    this.modelDataTable=dataValue.materials.rows;
                    this.total=dataValue.materials.total;
                }else{
                    this.$message.error("查询失败！");
                }
            })
        },
        chnageGoodState(row, column, cell, event){
            if(row.state.key && row.state.key!="NORMAL"){
                return;
            }
            this.$refs.multipleTable.toggleRowSelection(row);
        },
        inputClick(){
            this.currentPage=1;
            this.selectGood();
        },
        handleSelectionChange(val) {
            this.selectRow = val;
        },
        handleCurrentChange(currentPage){
            this.currentPage=currentPage;
            this.selectGood();
        },
        handleSizeChange(number){
            this.pageSize=number;
            this.selectGood();
        },
        checkboxInit(row,index){
            console.log(row.state.key);
            if(row.state && row.state.key!="NORMAL"){
                return 0;//不可勾选
            }else{
                return 1;
            }
        },
        tableClick(){
            this.dialogTableVisible = false;
            if(this.selectRow!=null && this.selectRow.length>0){
                for(var i=this.selectRow.length-1;i>=0;i--) {
                    var isAdd=true;
                    for(var m=0;m<this.tableData.length;m++){
                        if(this.selectRow[i].id==this.tableData[m].id){
                                this.$message.info("本次添加含有重复原料");
                            break;
                        }
                    }
                    if(isAdd) {
                        this.addColumn(this.itemActive);
                        this.tableData[this.itemActive + 1].code = this.selectRow[i].no;
                        this.tableData[this.itemActive + 1].name = this.selectRow[i].name;
                        this.tableData[this.itemActive + 1].id = this.selectRow[i].id;
                        this.tableData[this.itemActive + 1].count=0;
                        this.tableData[this.itemActive + 1].goodsSpec = this.selectRow[i].goodsSpec;
                        this.tableData[this.itemActive + 1].unitName = this.selectRow[i].purchaseUnit;
                        this.tableData[this.itemActive + 1].purchaseSpec = this.selectRow[i].purchaseSpec;
                        this.tableData[this.itemActive + 1].price = this.selectRow[i].purchasePrice.toFixed(2);
                        this.tableData[this.itemActive + 1].historyPrice = this.selectRow[i].purchaseNewPrice;
                    }
                }
                if(this.tableData[this.itemActive].id==""){
                    this.tableData.splice(this.itemActive, 1);
                }
            }
        },
         goBack() {
            this.router.go(-1);
        },
    }
}
</script>
<style scoped>
</style>